package com.haierp.service.logistics.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.Lists;
import com.haierp.service.IErpOrderService;
import com.haierp.util.yitao.YtDimensionCodeUtil;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.support.json.JSONParser;
import com.gargoylesoftware.htmlunit.javascript.host.Console;
import com.haierp.exception.ErpCommonException;
import com.haierp.model.ErpOrder;
import com.haierp.model.ShippingOrder;
import com.haierp.model.ShippingTrack;
import com.haierp.service.IShippingOrderService;
import com.haierp.service.logistics.IYunTongService;
import com.haierp.service.youzan.IYzService;
import com.haierp.util.HttpClientUtil;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
@Service("yunTongService")
public class YunTongServiceImpl implements IYunTongService {
	@Autowired
	private IShippingOrderService shippingOrderService;
	@Autowired
	private IYzService yzService;
	@Autowired
	private IErpOrderService erpOrderService;

	@Override
	public void createOrder(Long id) {
		ShippingOrder shippingOrder = shippingOrderService.selectById(id);
		if(shippingOrder == null) {
			throw new ErpCommonException("发货单号异常");
		}
		Map<String, Object> param = new HashMap<String, Object>();
    	Map<String, Object> paramDetail = new HashMap<String, Object>();
    	paramDetail.put("Key", "YTKEY001");
    	paramDetail.put("Action", "SubmitYunDan");
    	paramDetail.put("Yundan_code", shippingOrder.getShippingNo());
    	if(shippingOrder.getType() == 5) {
    		paramDetail.put("Kouan_name", "USA-C");
    	} else {
    		paramDetail.put("Kouan_name", "USA-P");
    	}
    	paramDetail.put("Ref_yundan_code", shippingOrder.getShippingNo());
    	paramDetail.put("Recv_user_name", shippingOrder.getReceiver());
    	paramDetail.put("Recv_user_phone", shippingOrder.getTelephone());
    	paramDetail.put("Recv_user_province", shippingOrder.getReceiverState());
    	paramDetail.put("Recv_user_city", shippingOrder.getReceiverCity());
    	paramDetail.put("Recv_user_area", shippingOrder.getReceiverDistrict());
    	paramDetail.put("Recv_user_addr", shippingOrder.getAddressDetail());
    	paramDetail.put("Recv_user_zipcode", "000000");
    	if(StringUtil.isNotBlank(shippingOrder.getIdCard())) {
    		paramDetail.put("Recv_user_id_no", shippingOrder.getIdCard());
    	} else {
    		paramDetail.put("Recv_user_id_no", "000000000000000000");
    	}
    	List<Map<String, Object>> goodsList = new ArrayList<>();
    	Map<String, Object> sbDetail = new HashMap<String, Object>();
    	List<ErpOrder> ErpOrderList = shippingOrderService.queryShippingOrderDetail(shippingOrder.getErpOrderId());
    	Double sbValue = 0D;
    	for(int i=0; i<ErpOrderList.size(); i++) {
    		ErpOrder erpOrder = ErpOrderList.get(i);
    		Map<String, Object> goods = new HashMap<String, Object>();
    		
    		String itemName = erpOrder.getItemName();
    		String itemBrand1 = erpOrder.getBrand();
    		String itemBrand = erpOrder.getBrand();
    		itemBrand = itemBrand.substring(0, itemBrand.indexOf("->"));
    		itemBrand1 = itemBrand1.substring(itemBrand1.indexOf("->")+2, itemBrand1.length());
    		itemName = itemName.replace("直邮", "");
    		itemName = itemName.replace("拼邮", "");
    		itemName = itemName.replace("包税", "");
    		itemName = itemName.replace("国内快递", "");
    		itemName = itemName.replace("男款", "");
    		itemName = itemName.replace("女款", "");
    		itemName = itemName.replace("成人款", "");
    		itemName = itemName.replace("儿童款", "");
    		itemName = itemName.replace("大童男款", "");
    		itemName = itemName.replace("大童女款", "");
    		itemName = itemName.replace("小童女款", "");
    		itemName = itemName.replace("小童男款", "");
    		itemName = itemName.replace("婴儿款", "");
    		itemName = itemName.replace(itemBrand, "");
    		itemName = itemName.replace(itemBrand1, "");
    		goods.put("Brand_name", itemBrand);
    		goods.put("Chinese_title", itemName);
    		goods.put("Qty", erpOrder.getQuantity());
    		goods.put("Price", getDeclaredPrice(erpOrder.getSalePrice()));
    		goodsList.add(goods);
    		
    		sbValue = sbValue+(erpOrder.getQuantity()*erpOrder.getSalePrice());
    	}

    	paramDetail.put("Sb_value", getDeclaredPrice(sbValue));
    	sbDetail.put("Sb_detail", goodsList);
    	paramDetail.put("Data", sbDetail);
    	param.put("json", JSONObject.fromObject(paramDetail).toString());
    	//System.out.println(param);
    	String shippingNoStr = HttpClientUtil.post("http://api.yuntongexpress.cn/api.ashx", null, param, "2", "2");
    	//String shippingNoStr = HttpClientUtil.post("http://172.115.164.192/api.ashx", null, param, "2", "2");
    	JSONObject shippingNoJson = JSONObject.fromObject(shippingNoStr);
    	shippingOrder.setLogisticNo(shippingNoJson.getString("YunDan_Code"));
    	shippingOrderService.updateSelectiveById(shippingOrder);
    	if(!shippingOrder.getLogisticNo().equals("")) {
    		Map<String, String> LogisticsCompanyKey =  yzService.youzanGetLogisticsCompany();
    		if(ErpOrderList.size()==1 && ErpOrderList.get(0).getSalesName().equals("有赞")){
				yzService.youzanSendLogisticsOnline(ErpOrderList.get(0).getTargetNo(), shippingOrder.getLogisticNo(), LogisticsCompanyKey.get("运通快递"));
			} else if (ErpOrderList.get(0).getSalesName().equals("一桃平台") || ErpOrderList.get(0).getSalesId().equals(46)) {
				Map<String, Object> params = new HashMap<>();
				String path = "/yitao/api/order/deliver";
				try {
					EntityWrapper<ErpOrder> erpList = new EntityWrapper<ErpOrder>();
					erpList.where("target_no={0}", ErpOrderList.get(0).getTargetNo());
					List<ErpOrder> list = erpOrderService.selectList(erpList);
					params.put("deliveryCompanyName", "运通速运");//快递名称  yuntong  运通速运
					params.put("orderCode", list.get(0).getTargetNo());//一桃订单ID
					params.put("deliveryNo", shippingOrder.getLogisticNo());//快递编号
					List<Long> itemIdList = Lists.newArrayList();
					if (list != null && list.size() != 0) {
						for (ErpOrder erpOrder : list) {
							itemIdList.add(erpOrder.getItemId());
						}
						if (itemIdList != null && itemIdList.size() != 0) {
							params.put("itemIdList", itemIdList);
						}
					}
					YtDimensionCodeUtil.yitaoHttpPostRequest(path, params, "post");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
    	}
	}
	
	private String getDeclaredPrice(Double salePrice) {
		salePrice = salePrice/7;
		return String.format("%.2f", salePrice);
	}
	

}
